#include <basic/errcode.h>
#include <basic/http.h>

char *url_encode(char *str, int len, char *str_enc)
{/*{{{*/
    int x, y;

    if(!str || len <= 0)
    {
        if(str_enc) CLR_BUF(str_enc);
        return(NULL);
    }
    if(str_enc)
        CLR_BUF(str_enc);
    else
        ALLOC_MULTI_RETERR(str_enc, char, len*3+1, NULL);

    for(x=0, y=0; len--; x++, y++)
    {
        if(str[x] == ' ')
        {   str_enc[y]='+';   }
        else if(str[x] == '-' || str[x] == '.' || str[x] == '_' ||
                (str[x] >= '0' && str[x] <= '9') ||
                (str[x] >= 'A' && str[x] <= 'Z') ||
                (str[x] >= 'a' && str[x] <= 'z'))
        {   str_enc[y]=str[x];   }
        else
        {
            str_enc[y++]='%';
            expand_to_str((unsigned char *)str+x, 1, str_enc+y);
            y++;
        }
    }
    str_enc[y]=ZERO;

    return (str_enc);
}/*}}}*/

char *url_decode(char *str_enc, int len, char *str)
{/*{{{*/
    int x, y;

    if(!str_enc || len <= 0)
    {
        if(str) CLR_BUF(str);
        return(NULL);
    }
    if(str_enc)
        CLR_BUF(str);
    else
        ALLOC_MULTI_RETERR(str, char, len+1, NULL);

    for(x=0, y=0; len--; x++, y++)
    {
        if(str_enc[x] == '+')
        {   str[y]=' ';  }
        else if(str_enc[x] == '%' && len >= 2 &&
                isxdigit(str_enc[x+1]) && isxdigit(str_enc[x+2]))
        {
            collapse_from_str(str_enc+x+1, 2, (unsigned char *)str+y);
            x+=2;
            len-=2;
        }
        else
        {   str[y]=str_enc[x];   }
    }
    str[y]=ZERO;

    return(str);
}/*}}}*/

/*
GET|POST URL HTTP/1.1<CRLF>
Accept-Language: zh-cn<CRLF>
Connection: Keep-Alive<CRLF>
Host: www.site.com<CRLF>
User-Agent: <CRLF>
Content-Length: nn<CRLF>
Content-Type: application/x-www-form-urlencoded<CRLF>
Accept-encoding: gzip<CRLF><CRLF>
POSTDATA

HTTP/1.1 CODE DESC<CRLF>
Server: Microsoft-IIS/4.0<CRLF>
Date: Mon, 3 Jan 2005 13:13:33 GMT<CRLF>
Last-Modified: Mon, 11 Jan 2004 13:23:42 GMT<CRLF>
Content-Type: text/html<CRLF>
Content-Length: 90<CRLF><CRLF>
<html>
<head>
<title>解读HTTP包示例</title></head><body>
Hello WORLD!
</body>
</html>

*/
